package com.dxs.Controller;

import com.dxs.Entity.EntityUser;
import com.dxs.Entity.EntityUserData;
import com.dxs.Mapper.FilesMapper;
import com.dxs.Mapper.ServerMapper;
import com.dxs.Service.FileService;
import com.dxs.Service.Impl.FileServiceImpl;
import com.dxs.Util.CreateSnowID;
import com.dxs.Util.SnowFlakeGenerateIdWorker;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private FileServiceImpl fileService;

    @Resource
    private FilesMapper filesMapper;

    @Resource
    private ServerMapper serverMapper;
    @PostMapping("/login")
    public ResultBean login(@RequestParam("username") String account, @RequestParam("password") String password){
        EntityUser user = filesMapper.login(account,password);
        if (user != null){
            user.password = null;
            serverMapper.updateUserStatus(user.getAccount(), 1);
            return ResultBean.loginSuccess("登录成功",user);
        }else {
            return ResultBean.Error("账号密码不正确！");
        }

    }

    @PostMapping("/file/formal/upLoad")
    public ResultBean<String> fileUploadFormal(
            @RequestParam(value = "file") MultipartFile file,
            @RequestParam(value = "dataMakerID") String dataMakerID,
            @RequestParam(value = "username") String uname,
            @RequestParam(value = "uid") int uid,
            @RequestParam(value = "typeCode") int typeCode) throws IOException {
        if (file.isEmpty()) throw new FileNotFoundException();
        System.out.println("已收到上传的文件"+file);
        if (dataMakerID == "") dataMakerID = String.valueOf(CreateSnowID.getNewIdBySnow());
        String returnUrl = fileService.uploadFileFormal(file,uname,uid, dataMakerID, typeCode);
        if ( returnUrl != ""){
            return ResultBean.uploadSuccess("上传成功",returnUrl);
        }
        return ResultBean.uploadError("上传失败","");
    }


    @PostMapping("/register")
    public ResultBean<String> register(@RequestParam(value = "account") String account,
                                       @RequestParam(value = "password") String password,
                                       @RequestParam(value = "passwordRepeat") String passwordRepeat,
                                       @RequestParam(value = "username") String username){
        String id = String.valueOf(CreateSnowID.getNewIdBySnow());
        int loginstatus = 0;
        int status = 0;
        if (filesMapper.register(username,account,password,id,status, loginstatus) > 0){
            return ResultBean.uploadSuccess("注册成功！","");
        }else {
            return ResultBean.Error("注册失败");
        }
    }


}
